package com.qys.livesMall.open.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.ParamCheckUtil;
import com.qys.livesMall.open.modal.dto.mail.ExpressInquiryDTO;
import com.qys.livesMall.open.modal.dto.mail.MonitorSubscriptionDTO;
import com.qys.livesMall.kafka.entity.ExpressInquiryVO;
import com.qys.livesMall.open.service.ExpressInquiryService;
import com.qys.livesMall.open.utils.KdApiUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Admin
 */

@Service
@Slf4j
public class ExpressInquiryServiceImpl implements ExpressInquiryService {

    /**
     * redis快递查询前缀
     */
    public static final String EXPRESS_TRACK = "expressTrack_";
    /**
     * 响应状态
     */
    public static final String SUCCESS = "Success";

    @Resource
    private RedisCache redisCache;

    @Override
    public ExpressInquiryVO expressTrackQuery(ExpressInquiryDTO expressInquiryDTO) {
        log.info("expressTrackQuery start");

        //参数校验
        ParamCheckUtil.checkField(expressInquiryDTO, true);

        //请求缓存
        ExpressInquiryVO resultJson =  redisCache.getCacheObject(EXPRESS_TRACK + expressInquiryDTO.getLogisticCode());
        if(null != resultJson){
            log.info("expressTrackQuery success from redis");
            return resultJson;
        }

        //请求三方接口
        log.info("expressTrackQuery success from api");
        ExpressInquiryVO inquiryVO;
        try {
            String resultJsonStr = KdApiUtil.expressInquiry(expressInquiryDTO);
            inquiryVO = JSONObject.parseObject(resultJsonStr, ExpressInquiryVO.class);
        } catch (Exception e) {
            throw new QysException("expressTrackQuery error");
        }

        //设置缓存
        if(inquiryVO.getSuccess()){
            redisCache.setCacheObject(EXPRESS_TRACK + expressInquiryDTO.getLogisticCode(), inquiryVO, 3L, TimeUnit.HOURS);
        }

        return inquiryVO;
    }

    @Override
    public void monitorSubscription(MonitorSubscriptionDTO dto) {
        log.info("monitorSubscription start");

        //参数校验
        ParamCheckUtil.checkField(dto,true);

        //发送请求
        String resultStr;
        try {
            resultStr = KdApiUtil.monitorSubscription(dto);
        } catch (Exception e) {
            throw new QysException("monitorSubscription error");
        }

        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        if(!(Boolean) jsonObject.get(SUCCESS)){
            throw new QysException((String) jsonObject.get("Reason"));
        }
    }

}
